package SearchLucene;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import Classes.*;
import IndexingLucene.MyIndexReader;

public class QueryRetrievalModel {

	protected MyIndexReader ireader;
	private Directory directory;
	private DirectoryReader dreader;
	private IndexSearcher isearcher;

	public QueryRetrievalModel(MyIndexReader ixreader) {
		try {
			directory = FSDirectory.open(Paths.get(Path.IndexTextDir));
			dreader = DirectoryReader.open(directory);
			isearcher = new IndexSearcher(dreader);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	public List<Document> retrieveQuery(Classes.Query aQuery, int TopN) throws Exception {
		List<Document> rankedList = new ArrayList<Document>();
		/**
		 * [class] queryparser.classic.QueryParser:
		 * This class is generated by JavaCC. The most important method is QueryParserBase.parse(String).
		 *  
		 * [constructor] QueryParser(String f, Analyzer a):
		 * Create a query parser.
		 * 
		 * [method inherited] Query QueryParserBase.parse(String query):
		 * Parses a query string, returning a Query.
		 * 
		 * 这里直接用WhitespaceAnalyzer是因为ExtractQuery中的topic's title部分已经处理完毕。
		 */
		Query theQ = new QueryParser("CONTENT", new WhitespaceAnalyzer()).parse(aQuery.getQueryContent()); // Return a query object
		ScoreDoc[] scoreDocs = isearcher.search(theQ, TopN).scoreDocs;
		for(ScoreDoc hit : scoreDocs) {
			rankedList.add(new Document(hit.doc + "", // docid 
					       				dreader.document(hit.doc).get("DOCNO"), // docno
					       				/**
					       				 * [field] ScoreDoc.score:
					       				 * The score of this document for the query.
					       				 */
					       				hit.score // doc score
			));
		}
		
		return rankedList;
	}
}
